package com.ks.api.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ks.api.entity.KsEventData;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 快手事件数据Mapper接口
 */
@Mapper
public interface KsEventDataMapper extends BaseMapper<KsEventData> {
    
    /**
     * 根据事件ID、用户ID和事件时间检查记录是否存在
     *
     * @param eventId 事件ID
     * @param openId 用户ID
     * @param eventTime 事件时间
     * @return 存在返回1，不存在返回0
     */
    @Select("SELECT COUNT(1) FROM ks_event_data WHERE event_id = #{eventId} AND open_id = #{openId} AND event_time = #{eventTime}")
    int checkExists(@Param("eventId") String eventId, @Param("openId") String openId, @Param("eventTime") String eventTime);
    
    /**
     * 查询最近的事件数据
     *
     * @param startTime 开始时间
     * @param limit 查询条数限制
     * @return 事件数据列表
     */
    @Select("SELECT * FROM ks_event_data WHERE create_time >= #{startTime} ORDER BY create_time DESC LIMIT #{limit}")
    List<KsEventData> findRecentEvents(@Param("startTime") Date startTime, @Param("limit") int limit);
    
    /**
     * 根据用户昵称和nickId查询事件数据（分页）
     */
    @Select("<script>" +
            "SELECT e.* FROM ks_event_data e " +
            "JOIN ks_user u ON e.open_id = u.open_id " +
            "WHERE 1=1 " +
            "<if test='nickname != null and nickname != \"\"'>" +
            "   AND u.nickname LIKE CONCAT('%', #{nickname}, '%') " +
            "</if>" +
            "<if test='nickId != null and nickId != \"\"'>" +
            "   AND u.nick_id = #{nickId} " +
            "</if>" +
            "AND (e.status = 0 OR e.status IS NULL) " +
            "ORDER BY e.event_time DESC" +
            "</script>")
    IPage<KsEventData> findEventsByNickname(Page<?> page, 
            @Param("nickname") String nickname,
            @Param("nickId") String nickId);
    
    /**
     * 获取指定时间范围内的统计数据
     */
    @Select("SELECT " +
            "COUNT(*) as count, " +
            "SUM(CASE WHEN e.cost/1000 > #{topPrice} THEN #{topPrice} ELSE e.cost/1000 END) as total_cost " +
            "FROM ks_event_data e " +
            "JOIN ks_user u ON e.open_id = u.open_id " +
            "WHERE u.nickname LIKE CONCAT('%', #{nickname}, '%') " +
            "AND e.event_time BETWEEN #{startTime} AND #{endTime}")
    Map<String, Object> getStatsByDateRange(@Param("nickname") String nickname,
                                          @Param("startTime") LocalDateTime startTime,
                                          @Param("endTime") LocalDateTime endTime,
                                          @Param("topPrice") BigDecimal topPrice);

    /**
     * 获取指定时间范围内的事件cost数据
     */
    @Select("<script>" +
            "SELECT e.cost FROM ks_event_data e " +
            "JOIN ks_user u ON e.open_id = u.open_id " +
            "WHERE 1=1 " +
            "<if test='nickname != null and nickname != \"\"'>" +
            "   AND u.nickname LIKE CONCAT('%', #{nickname}, '%') " +
            "</if>" +
            "<if test='nickId != null and nickId != \"\"'>" +
            "   AND u.nick_id = #{nickId} " +
            "</if>" +
            "AND (e.status = 0 OR e.status IS NULL) " +
            "AND e.event_time BETWEEN #{startTime} AND #{endTime}" +
            "</script>")
    List<BigDecimal> getEventCostsByDateRange(
            @Param("nickname") String nickname,
            @Param("nickId") String nickId,
            @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime);
            
    /**
     * 查询所有事件数据（分页）
     */
    @Select("<script>" +
            "SELECT e.*, u.nickname, u.nick_id, u.status as user_status FROM ks_event_data e " +
            "LEFT JOIN ks_user u ON e.open_id = u.open_id " +
            "WHERE 1=1 " +
            "<if test='nickId != null and nickId != \"\"'>" +
            "   AND u.nick_id = #{nickId} " +
            "</if>" +
            "<if test='nickname != null and nickname != \"\"'>" +
            "   AND u.nickname LIKE CONCAT('%', #{nickname}, '%') " +
            "</if>" +
            "<if test='startTime != null and startTime != \"\"'>" +
            "   AND e.event_time >= #{startTime} " +
            "</if>" +
            "<if test='endTime != null and endTime != \"\"'>" +
            "   AND e.event_time &lt;= #{endTime} " +
            "</if>" +
            "ORDER BY e.event_time DESC" +
            "</script>")
    IPage<KsEventData> findAllEvents(Page<?> page,
            @Param("nickId") String nickId,
            @Param("nickname") String nickname,
            @Param("startTime") String startTime,
            @Param("endTime") String endTime);
    
    /**
     * 获取指定时间范围内的所有事件cost数据
     */
    @Select("<script>" +
            "SELECT e.cost FROM ks_event_data e " +
            "LEFT JOIN ks_user u ON e.open_id = u.open_id " +
            "WHERE 1=1 " +
            "<if test='nickId != null and nickId != \"\"'>" +
            "   AND u.nick_id = #{nickId} " +
            "</if>" +
            "<if test='nickname != null and nickname != \"\"'>" +
            "   AND u.nickname LIKE CONCAT('%', #{nickname}, '%') " +
            "</if>" +
            "<if test='startTime != null'>" +
            "   AND e.event_time >= #{startTime} " +
            "</if>" +
            "<if test='endTime != null'>" +
            "   AND e.event_time &lt;= #{endTime} " +
            "</if>" +
            "</script>")
    List<BigDecimal> getAllEventCostsByDateRange(
            @Param("startTime") String startTime,
            @Param("endTime") String endTime,
            @Param("nickId") String nickId,
            @Param("nickname") String nickname);

    /**
     * 更新用户状态
     */
    @Update("UPDATE ks_user SET status = #{status} WHERE nick_id = #{nickId}")
    int updateUserStatus(@Param("nickId") String nickId, @Param("status") Integer status);
    
    /**
     * 更新指定用户在指定时间范围内的事件状态
     */
    @Update("<script>" +
            "UPDATE ks_event_data e " +
            "JOIN ks_user u ON e.open_id = u.open_id " +
            "SET e.status = 1 " +
            "WHERE u.nick_id = #{nickId} " +
            "AND e.event_time >= #{startTime} " +
            "AND e.event_time &lt;= #{endTime} " +
            "AND (e.status = 0 OR e.status IS NULL)" +
            "</script>")
    int updateEventStatus(
            @Param("nickId") String nickId,
            @Param("startTime") String startTime,
            @Param("endTime") String endTime);
} 